package app_demo.io;

import org.junit.Test;

import java.io.*;

/**
 * @Description 读取本地txt文件
 * @Author Firenut
 * @Date 2023-02-05 14:56
 */
public class InputStreamTest {
    @Test
    public void test() {
//        read1("hello.txt");
        copyFile("hello.txt");
    }

    /**
     *  拷贝文件
     */
    public void copyFile(String fileName) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(fileName));
            bos = new BufferedOutputStream(new FileOutputStream("hello1.txt"));
            byte[] buff = new byte[1024];
            int hasRead;
            while ((hasRead = bis.read(buff)) != -1) { //每次从缓冲区读取byte数组长度的字节
                bos.write(buff, 0, hasRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (bis != null) {
                    bis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 测试 BufferInputStream
     * @param fileName
     */
    public void read1(String fileName) {
        InputStream is = null;
        BufferedInputStream bi = null;
        try {
            is = new FileInputStream(fileName);
            bi = new BufferedInputStream(is);
            int hasRead = 0;
            byte[] buf = new byte[1024];
            while ((hasRead = bi.read(buf)) != -1) {
                System.out.println(new String(buf, 0, hasRead));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if (bi != null) {
                    bi.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

        /**
         * 测试 read(byte[]buf)
         * @param fileName
         */
    public void read(String fileName) {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(fileName);
            byte[] buf = new byte[1024];
            int hasRead = 0;
            while ((hasRead = inputStream.read(buf)) != -1) {
                System.out.println(new String(buf, 0, hasRead));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}